package com.ygo.feihua;

import android.content.*;
import android.graphics.*;
import android.net.*;
import android.os.*;
import android.support.design.widget.*;
import android.support.v4.app.*;
import android.support.v4.view.*;
import android.support.v4.widget.*;
import android.support.v7.app.*;
import android.support.v7.widget.*;
import android.view.*;
import android.view.View.*;
import android.view.animation.*;
import android.widget.*;
import cn.bmob.v3.datatype.*;
import cn.bmob.v3.exception.*;
import cn.bmob.v3.listener.*;
import com.qnw.CardGroupManagement.service.*;
import com.yalantis.ucrop.*;
import com.ygo.feihua.BmobTable.*;
import com.ygo.feihua.Management.*;
import com.ygo.feihua.fragment.*;
import com.ygo.feihua.service.*;
import com.ygo.feihua.util.*;
import com.yuyh.library.imgsel.ui.*;
import java.io.*;
import java.util.*;

import android.view.animation.AnimationUtils;
import com.mycard.ui.online.*;


public class CeHua extends AppCompatActivity  implements LogInListener,OnClickListener
{
	
	private FragmentManager fragmentManager;
	private DrawerLayout mDrawerLayout;
	
	//用户名
	private TextView main_name;
	private LinearLayout main_tool;
	private View tool_main,tool_shequ,tool_ourygo,tool_deck;
	public TabLayout main_tab;
	private CardView main_setting;
	private ImageView main_icon;
	
	private UserManagement um;
	private Gongju gj;
	private DialogUtils du;
	//当前fragment
	private Fragment dqFragment;
	
	MainBottomBarFragment mainBottomBarFragment=new MainBottomBarFragment();
	
	private View msetting_tie_type;

	private View msetting_feihua;

	private int toolType;
	private final int TOOL_MAIN=1;
	private final int TOOL_SHEQU=2;
	private final int TOOL_OURYGO=3;
	private final int TOOL_DECK = 4;

	private final int PHOTO_REQUEST_GALLERY = 10;
    private final int PHOTO_REQUEST_CUT = 11;
	private final int EWM_SCANNING=12;
	public static final int AVATAR_PATH_RESULT=13;

	private FragmentMainLeft mainLeftFmt;
	
	
	public CardView getMain_setting(){
		return main_setting;
	}
	
	public void setSettingImage(String fileUrl){
		gj.tuxian(fileUrl,main_icon);
		// TODO: Implement this method
	}
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		//设置全屏  
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.cehua);
		
		if(SharedPreferenceUtil.getKgUploadLocation()){
		//开启上传位置信息的服务
		startService(new Intent(this,ServiceMap.class));
		}
		//开启社区消息回复监听
		startService(new Intent(this,ServiceMessageAlert.class));
		Intent inte=new Intent(this,ServiceDuelAssistant.class);
		inte.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startService(inte);
		
		//初始化工具类
		gj=Gongju.getdx(this);
		//检测是否有更新,不提示
		gj.checkUpdate(false);
		//初始化各种控件
        findViews();	
		
		//初始化主页面
        showDefaultFragment();
	}

	@Override
	public void onClick(View p1)
	{
		switch(p1.getId()){
			case R.id.ts_message:
				gj.checkLogin(this,ShequMessageAlert.class);
				break;
			case R.id.ts_fb:
				gj.checkLogin(this,ShequFabu.class);
				break;
			case R.id.main_name:
				mDrawerLayout.openDrawer(GravityCompat.START);
				//startActivity(new Intent(this,MyCardActivity.class));
				break;
			case R.id.main_setting:
				clickSetting();
				break;
		}
		
		// TODO: Implement this method
	}

	private void clickSetting(){
		switch(toolType){
			case TOOL_MAIN:
			case TOOL_OURYGO:
				startActivity(new Intent(CeHua.this,RobotFeihua.class));
				break;
			case TOOL_SHEQU:
				mainBottomBarFragment.shequSettingClick();
				break;
		}
		// TODO: Implement this method
	}
	
	@Override
	public void login(MyUser mu){
		sxUserInformation();
		// TODO: Implement this method
	}

	@Override
	public void logout(){	
		main_name.setText("未登录");
		// TODO: Implement this method
	}
	
    private void findViews() {
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
       	main_tool=(LinearLayout) findViewById(R.id.main_tool);
		tool_main=LayoutInflater.from(this).inflate(R.layout.tool_main,null);
		main_tab=(TabLayout) tool_main.findViewById(R.id.main_tab);
		tool_deck=LayoutInflater.from(this).inflate(R.layout.tool_deck,null);
		tool_shequ=LayoutInflater.from(this).inflate(R.layout.tool_shequ,null);
		tool_ourygo=LayoutInflater.from(this).inflate(R.layout.tool_ourygo,null);
		main_name=(TextView) findViewById(R.id.main_name);
		
		du=DialogUtils.getdx(this);
		
		ImageView ts_message,ts_fb;
		ts_message=(ImageView) tool_shequ.findViewById(R.id.ts_message);
		ts_fb=(ImageView) tool_shequ.findViewById(R.id.ts_fb);
		
		main_setting=(CardView) findViewById(R.id.main_setting);
		main_icon=(ImageView) findViewById(R.id.main_icon);
		
		msetting_tie_type=LayoutInflater.from(this).inflate(R.layout.msetting_tie_type,null);
		msetting_feihua=LayoutInflater.from(this).inflate(R.layout.msetting_feihua,null);
		
	//	mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
		
		tool_deck.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View p1)
				{
					startActivityForResult(new Intent(CeHua.this,NewWjxz.class).putExtra("lx",1).putExtra("path",Gongju.PATH_EZ_MANAGEMENT+"ydk_fenxiang/"),EWM_SCANNING);
					// TODO: Implement this method
				}
			});
		
		//初始化fragment管理
		fragmentManager = getSupportFragmentManager();
			
		
		mainLeftFmt=(FragmentMainLeft) fragmentManager.findFragmentById(R.id.main_left);
		
		um=UserManagement.getDx();
		um.addLogInLostener(this);
		
		if(um.getUser()!=null){
			main_name.setText(um.getUser().getUsername());	
		}else{
			main_name.setText("未登录");
		}
		
		ts_message.setOnClickListener(this);
		ts_fb.setOnClickListener(this);
		main_name.setOnClickListener(this);
		main_setting.setOnClickListener(this);
	
		main_setting.setOnLongClickListener(new OnLongClickListener(){

				@Override
				public boolean onLongClick(View p1)
				{
				
					switch(toolType){
						case TOOL_MAIN:
							if (um.getUser() != null && um.getUser().getUser_qx() == 1){
								startActivity(new Intent(CeHua.this, ShequAddTieType.class));
							}
							break;
						case TOOL_SHEQU:
							main_icon.setImageResource(R.drawable.ic_tie_type);
							mainBottomBarFragment.shequSettingLongClick();
							break;
					}
						// TODO: Implement this method
					return true;
				}
			});
    }
	
	private void sxUserInformation()
	{
		main_name.setText(um.getUser().getUsername());
	}
	
	public void setToolShequ(){
		if(toolType!=TOOL_SHEQU){
		toolType=TOOL_SHEQU;
		(main_tool.getChildAt(0)).startAnimation(AnimationUtils.loadAnimation(CeHua.this,R.anim.out_from_top));
		main_tool.removeAllViews();
		main_tool.addView(tool_shequ);
		tool_shequ.startAnimation(AnimationUtils.loadAnimation(CeHua.this,R.anim.in_from_top));
		TieType tt= mainBottomBarFragment.getShequType();
		if(tt==null){
		main_icon.setImageResource(R.drawable.ic_tie_type);
		}else{
			gj.tuxian(tt.getIcon(),main_icon);
		}
		}
	}
	
	public void setToolMain(){
		if(toolType!=TOOL_MAIN){
		toolType=TOOL_MAIN;
		if(main_tool.getChildCount()!=0){
		(main_tool.getChildAt(0)).startAnimation(AnimationUtils.loadAnimation(CeHua.this,R.anim.out_from_down));
		}
		main_tool.removeAllViews();
		main_tool.addView(tool_main);
		tool_main.startAnimation(AnimationUtils.loadAnimation(CeHua.this,R.anim.in_from_down));
		main_icon.setImageResource(R.drawable.feihua);
		}
	}
	
	public void setToolOurygo(){
		if(toolType!=TOOL_OURYGO){
		toolType=TOOL_OURYGO;
		if(main_tool.getChildCount()!=0){
			(main_tool.getChildAt(0)).startAnimation(AnimationUtils.loadAnimation(CeHua.this,R.anim.out_from_down));
		}
		main_tool.removeAllViews();
		main_tool.addView(tool_ourygo);
		tool_ourygo.startAnimation(AnimationUtils.loadAnimation(CeHua.this,R.anim.in_from_down));
		main_icon.setImageResource(R.drawable.feihua);
		}
	}
	
	public void setToolDeck(){
		if(toolType!=TOOL_DECK){
		toolType=TOOL_DECK;
		if(main_tool.getChildCount()!=0){
			(main_tool.getChildAt(0)).startAnimation(AnimationUtils.loadAnimation(CeHua.this,R.anim.out_from_down));
		}
		main_tool.removeAllViews();
		main_tool.addView(tool_deck);
		tool_deck.startAnimation(AnimationUtils.loadAnimation(CeHua.this,R.anim.in_from_down));	
		main_icon.setImageResource(R.drawable.feihua);
		}
	}
	

    //初始化侧滑
    private void showDefaultFragment() {
		
	    dqFragment=mainBottomBarFragment;
        fragmentManager.beginTransaction().add(R.id.flContent, dqFragment).commit();
		setToolMain();
    }

	private static long firstTime;
	
	
	//点退出键先判断侧滑是否关闭,然后再判断两次退出软件
    @Override
    public void onBackPressed()
	{

        if (isNavDrawerOpen())
		{
            closeNavDrawer();
        }else{
			if (!dqFragment.equals(mainBottomBarFragment))
			{	
				fragmentManager.beginTransaction().hide(dqFragment).show(mainBottomBarFragment).commit(); // 隐藏当前的fragment，显示下一个
				dqFragment = mainBottomBarFragment;
				//main_tool.removeAllViews();
				setToolMain();
			}else{

				if (firstTime + 2000 > System.currentTimeMillis())
				{
					//在软件关闭时关闭上传位置信息的服务
					stopService(new Intent(this, ServiceMap.class));
					stopService(new Intent(this,ServiceMessageAlert.class));
		
					stopService(new Intent(this, MyPushMessageReceiver.class));
					//OurygoApplication.exit();
					super.onBackPressed();
					//完全退出软件
					android.os.Process.killProcess(android.os.Process.myPid());  		
				//	super.onBackPressed();
				}else{
					gj.show("再按一次退出程序喵~");
				}
				firstTime = System.currentTimeMillis();
			}
		}
    }

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		// TODO: Implement this method

		//监听菜单键
		if (keyCode == KeyEvent.KEYCODE_MENU)
		{
			if (isNavDrawerOpen()) {
				//如果菜单是打开的则关闭菜单
				closeNavDrawer();
			} else {
			//如果菜单是关闭的打开菜单
			//mDrawerLayout.openDrawer(GravityCompat.START);
			}
		}
		return super.onKeyDown(keyCode, event);
	}
	
    protected boolean isNavDrawerOpen() {
        return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(GravityCompat.START);
    }

    protected void closeNavDrawer() {
        if (mDrawerLayout != null) {
            mDrawerLayout.closeDrawer(GravityCompat.START);
        }
    }

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		// TODO: Implement this method
		super.onActivityResult(requestCode, resultCode, data);
		switch(requestCode){
			case EWM_SCANNING:
				final String img_url=data.getStringExtra("path");
				mainBottomBarFragment.ParsingDeck(img_url);
				break;
			case AVATAR_PATH_RESULT:
				if(resultCode==RESULT_OK){
					if (data != null) {
						ArrayList<String> photos = data.getStringArrayListExtra(ISListActivity.INTENT_RESULT);			
						String pa=photos.get(0);
						startCropActivity(Uri.fromFile(new File(pa)),"tx_"+um.getUser().getUsername()+".png");		
					}
				}
				break;
			case UCrop.REQUEST_CROP:
				if(data!=null){
					mainLeftFmt.replaceAvatar(Gongju.PATH_OURYGO+"image/touxiang/"+"tx_"+um.getUser().getUsername()+".png");
				}
				break;
			case PHOTO_REQUEST_CUT:
				if (data != null) 
					mainLeftFmt.setPicToView(data);
				break; 
		}	

	}
	
	private void startCropActivity(Uri uri,String FileName) {
		UCrop ucrop = UCrop.of(uri, Uri.fromFile(new File(gj.PATH_GEN + "ygo助手/image/touxiang/", FileName)));

		ucrop = ucrop.withAspectRatio(1,1);

		//ucrop.withAspectRatio(16, 9) .withMaxResultSize(144, 144);
		UCrop.Options options = new UCrop.Options();
		//设置裁剪图片的保存格式 
		options.setCompressionFormat(Bitmap.CompressFormat.PNG); 
		//设置裁剪图片的图片质量
		options.setCompressionQuality(100);
		//设置你想要指定的可操作的手势
		//options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.ROTATE, UCropActivity.ALL); 
		//设置uCropActivity里的UI样式 
		/*options.setMaxScaleMultiplier(5);
		 options.setImageToCropBoundsAnimDuration(666); 
		 options.setDimmedLayerColor(Color.CYAN);
		 options.setOvalDimmedLayer(true);
		 options.setShowCropFrame(false); 
		 options.setCropGridStrokeWidth(10); 
		 options.setCropGridColor(Color.GREEN);
		 options.setCropGridColumnCount(2);
		 options.setCropGridRowCount(1);
		 ucrop.withOptions(options);*/
		ucrop.start(this);		
	}


   
	
	
}
